<template>
	<view class="page flex-col">
		<uni-nav-bar color="white" @clickLeft="back" :fixed="true" :background-color="navColor" status-bar
			left-icon="left" :border="false">
			<view class="top">
				活动分解
			</view>
		</uni-nav-bar>
		<view class="head"></view>
		<view class="group_4 flex-col">
			<view class="group_13 flex-row justify-between">
				<text class="text_3">活动大类</text>
				<view class="image-text_9 flex-row justify-between">
					<view class="text-group_1">
						<picker @change="bindPickerChange" :value="typeindex" range-key="name" :range="bigtypes">
							<view class="uni-input">{{typeindex>=0?bigtypes[typeindex].name:'请选择大类'}}</view>
						</picker>
					</view>
					<image class="thumbnail_15" referrerpolicy="no-referrer" src="../../static/icon/right.png" />
				</view>
			</view>
			<view class="divide"></view>

			<text class="text_4">小类（多选）</text>
			<view class="grid_3 flex-row">
				<view class="text-wrapper_2 flex-col" :class="['text-wrapper_2',{active:item.selected}]"
					v-for="item in smalltypes" @tap="selSmallcate(item)">
					<text class="text_5">{{item.name}}</text>
				</view>

			</view>
		</view>
		<block v-for="(item,index) in transformIndex">
			<view class="group_5 flex-col">
				<view class="justify-between"><text class="text_10">转化指标</text><text class="del" @tap="del(index)">删除</text></view>
				<view class="box_5 flex-row justify-between">
					<text class="text_11">负责部门</text>
					<view class="image-text_10 flex-row justify-between" @tap="departmentselect(index)">
						<view v-if="item.deptName" class="flex-col">
							<text  class="text-group_2_v">{{item.deptName}}</text>
							<text  class="text-group_2_full">{{item.deptFullName}}</text>
						</view>
						
						<text v-else class="text-group_2">请选择部门</text>
						
						<image class="thumbnail_16" referrerpolicy="no-referrer" src="../../static/icon/right.png" />
					</view>
				</view>
				<view class="divide"></view>
				<view class="box_6 flex-row justify-between">
					<text class="text_12">执行人</text>
					<view class="image-text_11 flex-row justify-end" @tap="userselect(index)">

						<text v-if="item.dueRealName" class="text-group_3_v">{{item.dueRealName}}</text>
						<text v-else class="text-group_3">请选择执行人</text>
						<image class="thumbnail_17" referrerpolicy="no-referrer" src="../../static/icon/right.png" />
					</view>
				</view>
				<view class="divide"></view>
				<view class="box_7 flex-row justify-between">
					<text class="text_19">产品</text>
					<view class="image-text_12 flex-row justify-between" @tap="selectproducts(index)">
						<text v-if="item.deptConversionMetricProducts.length==0" class="text-group_4">请选择产品</text>
						<text v-else class="text-group_4_sel">已选择 {{item.deptConversionMetricProducts.length}} 个产品</text>
						<image class="thumbnail_18" referrerpolicy="no-referrer" src="../../static/icon/right.png" />
					</view>
				</view>

				<block v-for="(item_v,index_v) in item.deptConversionMetricItems">
					<view class="divide"></view>
					<block v-if="item_v.isQuantified">
						<uni-swipe-action class="text-wrapper_18 ">
							<!-- 基础用法 -->
							<uni-swipe-action-item :right-options="options" @click="indexdelete(index,index_v)">
								<view class="flex-row align-center justify-between">
									<text class="text_20">{{item_v.title}}</text>
									<view class="image-text_12 flex-row justify-between align-center">
										<input type="number" v-model="item_v.targetNum" placeholder="请填写" />
										<text class="text_22">{{item_v.unit}}</text>
									</view>

								</view>
							</uni-swipe-action-item>
						</uni-swipe-action>

					</block>
					<block v-else>
						<uni-swipe-action class="text-wrapper_18 ">
							<!-- 基础用法 -->
							<uni-swipe-action-item :right-options="options" @click="indexdelete(index,index_v)">
								<text class="text_23">{{item_v.title}}</text>

								<uni-easyinput :styles="styles" v-model="item_v.targetValue"
									:placeholderStyle="placeholderStyle" type="textarea"
									placeholder="请填写"></uni-easyinput>
							</uni-swipe-action-item>
						</uni-swipe-action>
					</block>
				</block>
				<view class="divide"></view>
				<text class="text_25">添加自定义指标</text>
				<view class="add" @tap="addindex(index)">
					<view class="x"></view>
					<view class="y"></view>
				</view>
			</view>

		</block>
		<view class="box_8 flex-col">
			<text class="text_26">添加部门指标</text>
			<view class="add flexcenter" @tap="addTransformIndex">
				<view class="x"></view>
				<view class="y"></view>
			</view>
			<view class="group_14 flex-row justify-between">
				<view class="text-wrapper_10 flex-col" @tap="save(0)">
					<text class="text_27" >保存</text>
				</view>
				<view class="text-wrapper_11 flex-col" @tap="save(1)">
					<text class="text_28">确认分解</text>
				</view>
			</view>
			<view class="divide"></view>
		</view>
		<view class="group_8 flex-row justify-between">
			<view class="text-group_7 flex-col">
				<text class="text_29">{{model.title}}</text>
				<text class="text_30">{{model.startDate}} ~ {{model.endDate}}</text>
				<view class="flex-row justify-between"><text class="text_31">{{model.planningFileName}}</text>
				<view class="text-wrapper_12 flex-col" v-if="model.planningMd5">
					<text class="text_32" @tap="preview(model.planningMd5)">点击预览</text>
				</view>
				</view>
			</view>
			
		</view>
		<uni-popup ref="popup" type="center" background-color="#fff" border-radius="10px 10px 10px 10px">
			<view class="popbd">
				<view class="tr title">维护指标信息</view>
				<view class="tr"><text>名称</text><input type="text" v-model="index.title" placeholder="请填写指标名称" />
				</view>
				<view class="tr"><text>单位</text><input type="text" v-model="index.unit" placeholder="请填写单位" /></view>
				<view class="tr"><text>目标</text><input type="number" v-model="index.targetNum" placeholder="请填写目标值" />
				</view>
				<view class="btn">
					<view @tap="operate(0)">取消</view>
					<view @tap="operate(1)">确定</view>
				</view>
			</view>
		</uni-popup>
		<uni-popup ref="popup_v" type="center" background-color="#fff" border-radius="10px 10px 10px 10px">
			<view class="popbd">
				<view class="tr title">维护指标信息</view>
				<view class="tr"><text>名称</text><input type="text" v-model="index.title" placeholder="请填写指标名称..." />
				</view>
				<view class="tr"><uni-easyinput type="textarea" v-model="index.targetValue"
						placeholder-style="font-size:32rpx;color:#383838;" placeholder="请填写指标描述"></uni-easyinput></view>
				<view class="btn">
					<view @tap="operate_v(0)">取消</view>
					<view @tap="operate_v(1)">确定</view>
				</view>
			</view>
		</uni-popup>
		<user-select :show="showUser" @ok="okUser" @cancel="showUser=false">
		</user-select>
		<uni-popup ref="message" background-color="#faecd8">
						<view class="popup-content" :class="{ 'popup-height': type === 'left' || type === 'right' }"><text
								class="text">{{messageText}}</text></view>
					</uni-popup>
	</view>
</template>
<script>
	import helper from "../../utils/helper";
	import {
		agingApi as agingApi,
		targetApi as targetApi
	} from "../../utils/api";
	export default {
		data() {
			return {
				//小类固化指标
				templateIndex: [],
				treeoptions: { //单选模式(任意一项)
					label: 'name',
					children: 'children',
					multiple: false,
					nodes: false
				},
				messageText:"",
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#dd524d'
					}
				}],
				navColor: 'transparent',
				constants: {},
				bigtypes: [],
				smalltypes: [],
				typeindex: -1,
				model: {},
				checkList: [],
				tree: [],
				transformIndex: [],
				deptConversionMetricItems: [],
				index: {},
				currentindex: 0,
				showUser: false,
				userindex: 0,
				departmentindex:0,
				placeholderStyle: "color:#cccccc;font-size:32rpx",
				styles: {
					color: '#383838',
					fontSize: '50rpx'
				},

			};
		},
		onLoad(e) {
			debugger
			this.id = e.id
			this.getbigtype()
			this.getsmalltype()
			this.getinfo()
		},
		onShow() {
			debugger
			let that = this

			uni.$once("isRefresh", function(data) {
				that.transformIndex[data.index].deptConversionMetricProducts = []
				data.pros.forEach((item) => {
					that.transformIndex[data.index].deptConversionMetricProducts.push({
						productId: item.productId,
						targetNum: item.targetNum,
						productImage:item.productImage,
						productName:item.productName,
						unit: item.unit
					})
				});

			})
			uni.$once('selectSuccess',(data)=>{
				if(data.list.length>0){
					that.transformIndex[this.departmentindex].deptName=data.list[0].name
					that.transformIndex[this.departmentindex].deptCode=data.list[0].id
					that.transformIndex[this.departmentindex].deptFullName=data.list[0].fullName
					
				}
				
			})

		},
		onPageScroll(e) {

			const scrollTop = e.scrollTop; // 获取页面滚动位置
			if (scrollTop < 100) {
				this.navColor = `rgba(37,47,98, ${scrollTop / 100})`; // 根据滚动位置设置透明度
			} else {

				this.navColor = 'rgba(37,47,98, 1)'; // 滚动超过一定距离后设为不透明
			}
		},
		methods: {
			async save(type) {
				var input = {}
				let that = this
				if(type==1){
					if(this.typeindex==-1){
										this.messageText = `活动大类必填`
										this.$refs.message.open('center')	
										return
					}
					if (this.smalltypes.length==0){
						this.messageText = `小类必填`
						this.$refs.message.open('center')
					return
					}
					if (this.transformIndex.length==0){
						this.messageText = `转化指标必填`
						this.$refs.message.open('center')
						return
					}else{
						let flag=false
						let userarr=[]
						this.transformIndex.forEach((item,index)=>{
							if(!item.deptName){
								this.messageText = `转化指标${index+1}中负责部门必填`
								this.$refs.message.open('center')
								flag=true
								return
							}
							if(!item.dueRealName){
								this.messageText = `转化指标${index+1}中执行人必填`
								this.$refs.message.open('center')
								flag=true
								return
							}else{
								if(userarr.indexOf(item.dueUserCode)>-1){
									this.messageText = `执行人在别的部门指标中已存在`
									this.$refs.message.open('center')
									flag=true
									return
								}else{
									userarr.push(item.dueUserCode)
								}
								
							}
							
							if(item.deptConversionMetricProducts.length==0){
								this.messageText = `转化指标${index+1}中产品必填`
								this.$refs.message.open('center')
								flag=true
								return
							}else{
								item.deptConversionMetricProducts.forEach((item_2,index_2)=>{
									if(!item_2.targetNum&&!item2.targetNum){
										this.messageText = `转化指标${index+1}中${item_2.title}必填`
										this.$refs.message.open('center')
										flag=true
										return
									}
								})
							}
						})
						if(flag){
							return
						}
					}
				}
				
				
				
				input.id = this.id;
				if(this.typeindex!=-1){
					input.eventCategoryId = this.bigtypes[this.typeindex].id
				}
				
				input.title = this.model.title
				input.activityCategorys = []
				//小类赋值
				if (this.smalltypes) {
					this.smalltypes.forEach((item) => {
						if (item.selected) {
							input.activityCategorys.push({
								activityCategoryId: item.value
							})
						}
					})

				}
				//部门指标赋值
				input.deptConversionMetrics = []
				if (this.transformIndex) {
					input.deptConversionMetrics = this.transformIndex
				}
				
				if(type==1){
					var result = await agingApi.fjSumit(input);
					if(result.code==0){
						this.back()
					}
				}else{
					var result = await agingApi.fjSave(input);
					if(result.code==0){
						this.back()
					}
				}
				
			},
			//选择人员
			userselect(index) {
				this.showUser = true
				this.userindex = index
			},
			departmentselect(index) {
				this.departmentindex = index
				
				uni.navigateTo({
					url:`/pages/chooseBm/chooseBm?arr=${JSON.stringify(this.checkList)}&prop=${JSON.stringify({
					label: 'name',
					children: 'children',
					multiple:false,
					nodes:false
				})}`
				})
			},


			okUser(data) {

				this.showUser = false
				this.transformIndex[this.userindex].dueUserCode = data.loginName
				this.transformIndex[this.userindex].dueRealName = data.userName
			},
		
			//获取
			async getinfo() {

				var result = await agingApi.getplanningscheme(this.id);
				if (result) {
					this.model = result.data

					if (this.model.eventCategoryId != '00000000-0000-0000-0000-000000000000') {
						this.bigtypes.forEach((item, index) => {
							if (item.id == this.model.eventCategoryId) {
								this.typeindex = index
							}
						})
					}
					if (this.model.activityCategorys) {
						this.model.activityCategorys.forEach((item) => {
							if (this.smalltypes) {
								this.smalltypes.forEach((item2) => {
									if (item.activityCategoryId == item2.value) {
										item2.selected = true
									}
								})
							}
						})

					}
					this.transformIndex=this.model.deptConversionMetrics
				}

			},
			//获取大类数据源
			async getbigtype() {

				var result = await agingApi.getbigtype({});
				if (result) {
					this.bigtypes = []
					let arr = result.data
					if (arr) {
						arr.forEach((item) => {
							this.bigtypes.push({
								name: item.name,
								id: item.id
							})
						})
					}
				}

			},
			//获取小类数据源
			async getsmalltype() {

				var result = await agingApi.getsmalltype({});
				if (result) {
					this.smalltypes = []
					let arr = result.data
					if (arr) {
						arr.forEach((item) => {
							this.smalltypes.push({
								name: item.name,
								value: item.id
							})
						})
					}
				}

			},
			//大类选择
			bindPickerChange: function(e) {
				this.typeindex = e.detail.value
			},
			//预览
			preview(md5) {
				helper.openFile(md5);
			},
			//增加部门指标
			addTransformIndex() {
				debugger
				var temp=[]
				if(this.templateIndex.length>0){
					this.templateIndex.forEach((item)=>{
						temp.push({title:item.title,isQuantified:item.isQuantified,targetNum:item.targetNum,targetValue:item.targetValue,unit:item.unit})
					})
				}
				this.transformIndex.push({
					deptName: '',
					deptFullName:'',
					deptCode:'',
					dueUserCode: '',
					dueRealName:'',
					deptConversionMetricProducts:[],
					deptConversionMetricItems: temp
				})
			},
			del(index){
				this.transformIndex.splice(index, 1)
			},
			//指标项删除
			indexdelete(index, index_v) {
				this.transformIndex[index].deptConversionMetricItems.splice(index_v, 1)
			},
			//选择产品
			selectproducts(index) {
				debugger
				uni.removeStorageSync('seletedpro')
				if (this.transformIndex[index].deptConversionMetricProducts) {
					uni.setStorageSync('seletedpro', this.transformIndex[index].deptConversionMetricProducts)
				}

				uni.navigateTo({
					url: "/pages/disassemble/selectproducts?index=" + index
				})
			},
			getselectedproducts(data) {

			},
			//添加指标
			addindex(index) {

				this.currentindex = index
				var that = this
				uni.showActionSheet({
					title: '自定义指标类型',
					itemList: ['量化', '非量化'],
					success: function(res) {
						if (res.tapIndex == 0) {
							that.$refs.popup.open()
						} else if (res.tapIndex == 1) {
							that.$refs.popup_v.open()
						}
					},
					fail: function(res) {
						console.log(res.errMsg);
					}
				});
			},
			//
			operate(type) {
				if (type == 0) {
					this.$refs.popup.close()
				} else {
					if(!this.index.title){
						uni.showToast({
							title:'名称必填',
							icon:'none'
						})
						return
					}
					
					if(!this.index.unit){
						uni.showToast({
							title:'单位必填',
							icon:'none'
						})
						return
					}
					if(!this.index.targetNum){
						uni.showToast({
							title:'目标必填',
							icon:'none'
						})
						return
					}
					this.index.isQuantified = true
					this.transformIndex[this.currentindex].deptConversionMetricItems.push(this.index)
					this.index = {}
					this.$refs.popup.close()
				}
			},
			operate_v(type) {
				if (type == 0) {
					this.$refs.popup_v.close()
				} else {
					if(!this.index.title){
						uni.showToast({
							title:'名称必填',
							icon:'none'
						})
						return
					}
					if(!this.index.targetValue){
						uni.showToast({
							title:'目标必填',
							icon:'none'
						})
						return
					}
					
					this.index.isQuantified = false
					this.transformIndex[this.currentindex].deptConversionMetricItems.push(this.index)
					this.index = {}
					this.$refs.popup_v.close()
				}
			},
			//小类选择
			async selSmallcate(selected) {
				let seleted = []
				selected.selected = !selected.selected
				if (selected.selected) {
					var result = await agingApi.getindex(selected.value);
					if (result) {
						if (result.data) {
							result.data.forEach((item) => {
								if (!this.templateIndex.some(item2 => item2.id === item.id)) {
									this.templateIndex.push(item)
								}
							})
						}

					}
				}
			},
			back() {
				uni.navigateBack({
					delta: 1
				})
			},
		}
	}
</script>
<style lang="scss" scoped>
	@import '../common/common.scss';
	@import './index.scss';

</style>